<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: sqlrevert.class.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 */
defined('IN_TWCMS') || exit('Access Denied');

class sqlrevert extends base{
	public $db;
	public $G;
	public $userName;
	public $cacheFile;
	public $sqlName;

	function __construct() {
		$this->load_db();
		$sqlname = strC($_GET, 'sqlname');
		$volume = intget('volume', 1);
		$volumes = intget('volumes');

		$sqlfile = TWCMS_DATA.'backup'.D.$sqlname.D.$volume.'.sql';
		$status = 2;
		$msg = $pbr = $url = '';
		if(empty($sqlname) || preg_match('/\W/', $sqlname)) {
			$msg = '非法文件名';
		}elseif(!$this->getUser()){
			$msg = '获取用户名失败';
		}elseif(!$this->getSqlName()) {
			$msg = '获取缓存文件名失败';
		}elseif($sqlname != $this->sqlName) {
			$msg = '文件名和缓存文件名不相同';
		}elseif(!file_exists($sqlfile)) {
			$msg = '还原失败, '.$volume.'.sql 文件不存在';
		}elseif(!$identify = $this->getIdentify($sqlfile)) {
			$msg = '读取备份文件失败';
		}else{
			$sqlquery = splitsql(f_read($sqlfile));

			$querytrue = $queryfalse = 0;
			foreach($sqlquery as $sql) {
				if(trim($sql) != '') $this->db->query($sql) ? $querytrue++ : $queryfalse++;
			}
			
			if($volume < $volumes) {
				$msg = '还原 '.$volume.'.sql 完成 (ok:'.$querytrue.($queryfalse ? ' <font color=\'red\'>err:'.$queryfalse.'</font>' : '').')';
				$status = 1;
				$pbr = floor($volume/$volumes*100);
				$url = ADMNAME.'?mod=sqlrevert&sqlname='.$sqlname.'&volumes='.$volumes.'&volume='.++$volume;		
			}else{
				unlink($this->cacheFile);
				$msg = '还原完成！';
				$status = 0;
				$pbr = 100;
			}
		}
		exit('{"status":"'.$status.'","msg":"'.$msg.'","pbr":"'.$pbr.'","url":"'.$url.'"}');
	}

	//获取鉴定信息
	function getIdentify($file) {
		if(!is_file($file)) return false;
		if(@$fp = fopen($file, 'rb')) {
			$Identify = explode(',', base64_decode(preg_replace("/^# Identify: (\w+).*/s", "\\1", fgets($fp, 256))));
			fclose($fp);
			return $Identify;
		}
		return false;
	}

	//从COOKIE中获取用户名
	function getUser() {
		if(empty($_COOKIE[TW_COOKIEPRE.'admauth'])) return false;
		list($user, $pwd, $rands) = explode("\t", sys_auth($_COOKIE[TW_COOKIEPRE.'admauth'], 'DECODE'));
		if($user && $pwd && $rands) {
			$this->userName = $user;
			return true;
		}
		return false;
	}

	//获取SQL文件名
	function getSqlName() {
		if(empty($this->userName)) return false;
		$this->cacheFile = TWCMS_CACHE.$this->userName.'_sqlname.php';
		if(file_exists($this->cacheFile)) {
			$this->sqlName = f_read($this->cacheFile);
			return true;
		}
		return false;
	}
}